<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="转租车辆列表")
 */
class Sublease extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\VehicleSq();
        
    }

     /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->where("class_id",2)
                ->count();
            $list = $this->model
                ->where($where)
                ->where("class_id",2)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                foreach ($list as $k => $v){
                  
                    if(!empty($v['class_id'])){
                        $classification = Db::name('classification')->where('id',$v['class_id'])->field('title')->find();
                        if(!empty($classification)){
                            $v['class_name'] = $classification["title"];
                        }else{
                            $v['class_name'] = "";
                        }
                        $v['class_name'] = $classification["title"];
                    }else{
                        $v['class_name'] = "";
                    }
                    $list[$k] = $v;
                }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    } 

    
    /**
    * @NodeAnotation(title="添加")
    */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['titlt'])){
                $this->error('标题不能为空');
            }
            if(empty($post['level'])){
                $this->error('未找到指定参数1');
            }
            if(empty($post['power_type'])){
                $this->error('未找到指定参数2');
            }
            if(empty($post['spec_value'])){
                $this->error('分期估价不能为空');
            }
            $vehicle_bystages = $post['spec_value'];
            $data = [
                "class_id"=>2,
                "titlt"=>$post["titlt"],
                "bfirstletter"=>$post["bfirstletter"],
                "vehicle_brand"=>$post["vehicle_brand"],
                "level"=>$post["level"],
                "power_type"=>$post["power_type"],
                "mileage"=>$post["mileage"],
                "registration_time"=>$post["registration_time"],
                "model"=>$post["model"],
                "equipped_withdisplacement"=>$post["equipped_withdisplacement"],
                "vehicle_detection"=>$post["vehicle_detection"],
                "host_graphimg"=>$post["host_graphimg"],
                "real_shootingimg"=>$post["real_shootingimg"],
                "vehicle_color"=>$post["vehicle_color"],
                "create_time"=>time(),
                "status"=>1
            ];
            try {
               Db::name('vehicle_sq')->insert($data);
               $vehicle_id =  Db::name('vehicle_sq')->getLastInsID();
               foreach($vehicle_bystages as $k=>$v){
                    $datv = [
                        "vehicle_id"=>$vehicle_id,
                        "number_ofperiods"=>$v["number_ofperiods"],
                        "monthly_rentalamount"=>$v["monthly_rentalamount"]
                    ];
                    Db::name("vehicle_bystages_sq")->insert($datv);
               }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('保存成功') ;
        }else{
            $carbrand = Db::name("carbrand")->field("bfirstletter")->group("bfirstletter")->select()->toArray();
            $this->assign("carbrand",$carbrand);
            return $this->fetch();
        }
        
    }
 
     /**
    * @NodeAnotation(title="编辑")
    */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['titlt'])){
                $this->error('标题不能为空');
            }
            if(empty($post['level'])){
                $this->error('未找到指定参数');
            }
            if(empty($post['power_type'])){
                $this->error('未找到指定参数');
            }
            if(empty($post['spec_value'])){
                $this->error('分期估价不能为空');
            }
            $vehicle_bystages = $post['spec_value'];
            $data = [
                "titlt"=>$post["titlt"],
                "bfirstletter"=>$post["bfirstletter"],
                "vehicle_brand"=>$post["vehicle_brand"],
                "level"=>$post["level"],
                "power_type"=>$post["power_type"],
                "mileage"=>$post["mileage"],
                "registration_time"=>$post["registration_time"],
                "model"=>$post["model"],
                "equipped_withdisplacement"=>$post["equipped_withdisplacement"],
                "vehicle_detection"=>$post["vehicle_detection"],
                "host_graphimg"=>$post["host_graphimg"],
                "real_shootingimg"=>$post["real_shootingimg"],
                "vehicle_color"=>$post["vehicle_color"]
            ];
            try {
               Db::name("vehicle_sq")->where("id",$post["id"])->update($data);
               Db::name("vehicle_bystages_sq")->where("vehicle_id",$post["id"])->delete();
               foreach($vehicle_bystages as $k=>$v){
                    $datv = [
                        "vehicle_id"=>$post["id"],
                        "number_ofperiods"=>$v["number_ofperiods"],
                        "monthly_rentalamount"=>$v["monthly_rentalamount"]
                    ];
                    Db::name("vehicle_bystages_sq")->insert($datv);
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('保存成功');
        }else{
            $post = $this->request->param(); 
            $row = $this->model->where('id',$post['id'])->find();
            $carbrand = Db::name("carbrand")->field("bfirstletter")->group("bfirstletter")->select()->toArray();
            $this->assign("carbrand",$carbrand); 

            $vehicle_brand = Db::name("carbrand")->where("bfirstletter",$row["bfirstletter"])->field("id,name")->select()->toArray();
            $this->assign('vehicle_brand', $vehicle_brand); 
            $vehicle_bystages_sq = Db::name("vehicle_bystages_sq")->where("vehicle_id",$post['id'])->order("id asc")->select()->toArray();
            $this->assign("vehicle_bystages",json_encode($vehicle_bystages_sq)); 
            $this->assign('row', $row); 
            return $this->fetch();
        }
       
    }

    
    public function upload(){
        $file = $_FILES['file'];
     
        if (!isset($file['tmp_name']) || !$file['tmp_name']) {
            echo json_encode(array('code' => 401, 'msg' => '没有文件上传'));
            return false;
        }
        if ($file["error"] > 0) {
            echo json_encode(array('code' => 402, 'msg' => $file["error"]));
            return false;
        }
        $filename = time().rand(0, 1000);
        $ext = pathinfo($_FILES['file']['name'])['extension'];
        $filename = $filename . '.' . $ext;
        $upload_path = "resultfile/";
        
        $domain = ($this->isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']; //获取域名
        $save_path =$domain.'/' . $upload_path . $filename;
        if (!is_dir($upload_path)) {
            mkdir(iconv("UTF-8", "UTF-8", $upload_path), 0777, true);
        }
        if (move_uploaded_file($file["tmp_name"], $upload_path . $filename)) {
            echo json_encode(array('code' => 200, 'src' => $save_path));
        } else {
            echo json_encode(array('code' => 404, 'msg' => '上传失败'));
            return false;
        }
    }
 
    public function province(){
        if ($this->request->isAjax()) {
            $brand_id = $this->request->param('id');
            $list = Db::name("carbrand")->where("bfirstletter",$brand_id)->select()->toArray();
            $opt = "<option value=''>--请选择--</option>";
            foreach ($list as $k => $val) {
                $opt .= "<option value='{$val['name']}'>{$val['name']}</option>";
            }
            if ($opt) {
                exit(json_encode(array('opt' => $opt)));
            } else {
                exit(json_encode(array('status' => 1)));
            }
        }
    }

   

    
    

    
}